# -*- coding: utf-8 -*-
from django_redis import get_redis_connection
from redis import StrictRedis
import json
from django.conf import settings
import base64


class CacheUtils(object):
    def __init__(self):
        self.redis_conn = get_redis_connection('default')  # type:StrictRedis

    def data_encryption(self, data):
        """加密数据"""
        return base64.b64encode(data.encode("utf-8"))

    def data_decryption(self, data):
        """解密数据"""
        return base64.b64decode(data).decode("utf-8")

    def clear_user_info(self, token):
        self.redis_conn.delete(self.data_encryption(token))

    def save_user_info(self, token, user_info):
        # 设置过期时间
        user_info = json.dumps(user_info)
        self.redis_conn.set(self.data_encryption(token), self.data_encryption(user_info), settings.USER_LOGIN_EXPIRE)

    def get_user_info(self, token):
        user_info = self.redis_conn.get(self.data_encryption(token))
        user_info = self.data_decryption(user_info)
        return json.loads(user_info)
